<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-card class="box-card">
      <div class="query-card">
        <!-- <el-row type="flex" align="middle">
        <el-col :span="12">-->
        <div class="grid-content bg-purple search">
          <el-form ref="query" :model="query" label-width="100px">
            <el-form-item style="margin-bottom:0px" label="名称">
              <i slot="label" class="el-icon-search" style="font-size:20px"></i>
              <el-input style="width:360px" v-model="query.keywords" placeholder="请输入盲盒名称搜索"></el-input>
            </el-form-item>
            <el-form-item style="margin-bottom:0px" label="分类">
              <el-select style="width:360px" v-model="query.type" placeholder="请选择分类">
                <el-option label="全部" value="0"></el-option>
                <el-option label="天选之人" value="1"></el-option>
                <el-option label="无限盲盒" value="2"></el-option>
                <el-option label="寻宝" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <!-- </el-col> -->
        <!-- <el-col :span="12"> -->
        <div class="grid-content bg-purple-light">
          <el-button type="primary" @click="queryAsk">查询</el-button>
          <el-button @click="queryReset">重置</el-button>
        </div>
        <!-- </el-col>
        </el-row>-->
      </div>
    </el-card>

    <!-- 表格 -->
    <el-card class="box-card">
      <img
        v-if="baseApi== 'https://testouhun.wm2177.com'"
        class="watermark"
        style="right: 0;"
        src="@/assets/watermark.png"
      />
      <el-dropdown @command="addList" style="margin-bottom:20px" v-if="activeName==1">
        <el-button type="primary">
          添加模板
          <i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="1">天选之人</el-dropdown-item>
          <el-dropdown-item command="2">无限盲盒</el-dropdown-item>
          <el-dropdown-item command="3">寻宝</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="模板" name="1"></el-tab-pane>
        <el-tab-pane label="盲盒" name="0"></el-tab-pane>
      </el-tabs>
      <el-table
        :data="tableData"
        border
        :header-cell-style="{background:'#eee'}"
        v-loading="loading"
        style="width: 100%;margin-bottom:20px"
      >
        <el-table-column align="center" prop="id" label="ID"></el-table-column>
        <el-table-column align="center" label="封面图片">
          <template slot-scope="scope">
            <el-popover placement="top-start" title trigger="hover">
              <img :src="scope.row.img" alt style="max-width:250px" />
              <!-- <el-avatar shape="square" :size="150" fit="cover" :src="scope.row.img"></el-avatar> -->
              <el-avatar
                slot="reference"
                shape="square"
                :size="50"
                fit="scale-down"
                :src="scope.row.img"
              ></el-avatar>
              <!-- <img
                slot="reference"
                :src="scope.row.img"
                style="width: 60px;height: 60px"
              />-->
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="盲盒名称"></el-table-column>
        <el-table-column align="center" label="类型">
          <template slot-scope="scope">
            <div v-if="scope.row.type==1">天选之人</div>
            <div v-if="scope.row.type==2">无限盲盒</div>
            <div v-if="scope.row.type==3">寻宝</div>
            <div></div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="price" label="单价"></el-table-column>
        <el-table-column align="center" prop="id" label="是否预售">
          <template slot-scope="scope">
            <div v-if="scope.row.is_ys==1">是</div>
            <div v-if="scope.row.is_ys==0">否</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="单箱抽取次数">
          <template slot-scope="scope">
            <div v-if="scope.row.type==1">{{scope.row.extract_ci}}</div>
            <div v-if="scope.row.type==3">{{scope.row.extract_ci}}</div>
            <div v-if="scope.row.type==2">-</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="case_num" label="箱数" v-if="activeName==0"></el-table-column>
        <el-table-column align="center" label="是否上架" v-if="activeName==0">
          <template slot-scope="scope">
            <div v-if="scope.row.is_show==1">是</div>
            <div v-if="scope.row.is_show==0">否</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="no_get" label="总发数" v-if="activeName==0">
          <template slot-scope="scope">
            <div v-if="scope.row.type!=2">-</div>
            <div v-else>{{scope.row.no_get}}</div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          fixed="right"
          prop="no_get"
          label="矿难设置"
          width="100"
          v-if="activeName==0"
        >
          <template slot-scope="scope" v-if="scope.row.type==2">
            <el-button
              @click="handleFeedEdite(scope.row)"
              type="text"
              size="small"
            >{{scope.row.mine_id !=0?'修改':'设置'}}</el-button>
            <el-popconfirm
              v-if="scope.row.mine_id !=0"
              confirmButtonText="好的"
              cancelButtonText="不用了"
              icon="el-icon-info"
              iconColor="red"
              title="确定解绑矿难吗"
              @onConfirm="handleUnbind(scope.row)"
            >
              <el-button
                style="margin-left:10px;color:red"
                slot="reference"
                type="text"
                size="small"
              >解绑</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button
              @click="handleEdite(scope.row)"
              type="text"
              size="small"
              v-if="activeName==1"
            >编辑</el-button>
            <el-popconfirm
              confirmButtonText="好的"
              cancelButtonText="不用了"
              icon="el-icon-info"
              iconColor="red"
              title="确定复制新盲盒吗？"
              @onConfirm="copyMH(scope.row)"
            >
              <el-button
                style="margin-left:10px"
                slot="reference"
                type="text"
                size="small"
                v-show="activeName==1"
              >复制到新盲盒</el-button>
            </el-popconfirm>
            <el-popconfirm
              confirmButtonText="好的"
              cancelButtonText="不用了"
              icon="el-icon-info"
              iconColor="red"
              title="确定复制新模板吗？"
              @onConfirm="copyMB(scope.row)"
            >
              <el-button
                style="margin-left:10px;"
                slot="reference"
                type="text"
                size="small"
                v-show="activeName==1"
              >复制到新模板</el-button>
            </el-popconfirm>
            <el-popconfirm
              confirmButtonText="好的"
              cancelButtonText="不用了"
              icon="el-icon-info"
              iconColor="red"
              title="确定上架吗？"
              @onConfirm="grounding(scope.row)"
            >
              <el-button
                slot="reference"
                type="text"
                size="small"
                style="margin-left:10px"
                v-show="activeName==0 && scope.row.is_show==0"
              >上架盲盒</el-button>
            </el-popconfirm>

            <el-popconfirm
              confirmButtonText="好的"
              cancelButtonText="不用了"
              icon="el-icon-info"
              iconColor="red"
              title="确定下架吗？"
              @onConfirm="grounding(scope.row)"
            >
              <el-button
                slot="reference"
                type="text"
                size="small"
                style="margin-left:10px"
                v-show="activeName==0 && scope.row.is_show==1"
              >下架盲盒</el-button>
            </el-popconfirm>
            <el-button
              style="margin-left:10px"
              @click="addBoxNum(scope.row)"
              type="text"
              size="small"
              v-show="activeName==0 && scope.row.type==1"
            >添加箱数</el-button>
            <el-button
              style="margin-left:10px"
              @click="lookBoxNum(scope.row)"
              type="text"
              size="small"
              :disabled="scope.row.case_num==0"
              v-show="activeName==0 && scope.row.type==1"
            >查看在售箱数</el-button>
            <el-popconfirm
              confirmButtonText="好的"
              cancelButtonText="不用了"
              icon="el-icon-info"
              iconColor="red"
              title="这是一段内容确定删除吗？"
              @onConfirm="handleDel(scope.row)"
            >
              <el-button
                style="margin-left:10px;color:red"
                slot="reference"
                type="text"
                size="small"
              >删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align:right">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="currentPage"
          :total="total"
          @current-change="currentChange"
        ></el-pagination>
      </div>
    </el-card>
    <el-dialog title="矿难设置" :visible.sync="feedVisible" width="60%" :before-close="handleClose">
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="绑定矿难" prop="mine_id">
          <el-select v-model="ruleForm.mine_id" placeholder="请选择矿难">
            <el-option v-for="item in feedBacks" :key="item.id" :value="item.id" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="触发类型" prop="ctype">
          <el-select v-model="ruleForm.ctype" placeholder="请选择类型">
            <el-option value="1" label="发数"></el-option>
            <el-option value="2" label="金额"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="`达标值${ruleForm.ctype=='1'?'(发)':'(元)'}`" prop="reach_value">
          <el-input-number
            :min="50"
            v-model="ruleForm.reach_value"
            placeholder="填写达标值"
            :controls="false"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="入场倒计时(秒)" prop="in_seconds">
          <el-input-number
            :min="30"
            v-model="ruleForm.in_seconds"
            placeholder="填写入场倒计时"
            :controls="false"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="游戏倒计时(秒)" prop="reach_value">
          <el-input-number
            :min="30"
            v-model="ruleForm.game_seconds"
            placeholder="填写游戏倒计时"
            :controls="false"
          ></el-input-number>
        </el-form-item>
        <!-- : null, //
        : 0, //入场倒计时时间秒
        game_seconds: 0 //游戏倒计时时间秒-->

        <el-form-item>
          <el-button type="primary" @click="submitFeed('ruleForm')">立即绑定</el-button>
          <el-button @click="resetFeed('ruleForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 添加箱数 -->
    <el-dialog title="添加箱数" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <el-form ref="addform" :model="addform" label-width="80px">
        <el-form-item label="添加箱数">
          <el-input style="width:50%" v-model="addform.num" placeholder="填写箱数跟原本箱数相加"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addBoxNumSub">立即创建</el-button>
          <el-button @click="subCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 箱数列表 -->
    <el-drawer
      title="箱数列表"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="drawhandleClose"
    >
      <el-table
        :data="drawtableData"
        border
        style="width: 100%;margin-bottom:20px"
        :header-cell-style="{background:'#eee'}"
        v-loading="boxloading"
      >
        <el-table-column align="center" prop="id" label="ID"></el-table-column>
        <el-table-column align="center" prop="name" label="名称">
          <template slot-scope="scope">{{scope.row.name+'箱'}}</template>
        </el-table-column>
        <el-table-column align="center" prop="sum" label="总量"></el-table-column>
        <el-table-column align="center" prop="leftover" label="剩余量"></el-table-column>
        <el-table-column align="center" prop="over_time" label="开箱时间"></el-table-column>
      </el-table>
      <div style="text-align:right">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="boxcurrentPage"
          :total="boxtotal"
          @current-change="boxcurrentChange"
        ></el-pagination>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  blinboxList,
  delBox,
  copyBox,
  grounding,
  addBoxNum,
  lookBoxNum
} from '@/api/blindbox'
import { lists, bind, unbind, bindInfo } from '@/api/feedback'
import { parseTime } from '@/utils/index'
export default {
  name: 'BlindBoxList',
  data() {
    return {
      baseApi: process.env.VUE_APP_BASE_API,
      // 分页数据
      total: 0,
      currentPage: 1,
      pageSize: 10,
      //query
      query: {
        keywords: '',
        type: '0'
      },
      options: '',
      tableData: [],
      activeName: '1',
      loading: false,
      dialogVisible: false,
      addform: {
        num: '',
        id: ''
      },
      // 箱数分页数据
      boxtotal: 0,
      boxcurrentPage: 1,
      boxpageSize: 10,
      // 箱数列表
      drawer: false,
      direction: 'rtl',
      drawtableData: [],
      boxloading: false,
      boxid: '',
      feedBacks: [],
      feedVisible: false,
      ruleForm: {
        mine_id: null,
        ctype: '1', //计算类型:1=按发数,2=按金额
        reach_value: 50, //达标值
        in_seconds: 30, //入场倒计时时间秒
        game_seconds: 30 //游戏倒计时时间秒
      },
      rules: {
        mine_id: [{ required: true, message: '请选择矿池', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.getList()
  },
  activated() {
    this.currentPage = 1
    this.query.keywords = ''
    this.query.type = '0'
    this.activeName = '1'
    this.getList()
  },
  methods: {
    submitFeed(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          bind(this.ruleForm).then((res) => {
            if (res.st == 1) {
              this.$message({
                message: '绑定成功',
                type: 'success'
              })
              this.feedVisible = false
              this.getList()
            } else {
              this.$message.error(res.msg)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleUnbind(row) {
      unbind({
        box_id: row.id
      }).then((res) => {
        if (res.st == 1) {
          this.$message({
            message: '解绑成功',
            type: 'success'
          })
          this.getList()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    resetFeed(formName) {
      this.$refs[formName].resetFields()
      this.feedVisible = false
      this.ruleForm = {}
    },
    handleFeedEdite(row) {
      lists({
        page: 1,
        limit: 50
      }).then((res) => {
        this.feedBacks = res.data
      })
      this.ruleForm.mine_id = row.mine_id != 0 ? row.mine_id : null
      if (row.mine_id != 0) {
        bindInfo({
          box_id: row.id
        }).then((res) => {
          const obj = res.st
          this.ruleForm = {
            box_id: row.id,
            mine_id: row.mine_id,
            ctype: obj.ctype,
            reach_value: obj.reach_value,
            in_seconds: obj.in_seconds,
            game_seconds: obj.game_seconds
          }
          this.feedVisible = true
        })
      } else {
        this.ruleForm = {
          box_id: row.id,
          mine_id: null,
          ctype: '1',
          reach_value: 50,
          in_seconds: 30,
          game_seconds: 30
        }
        this.feedVisible = true
      }
    },
    // 箱数列表
    async lookBoxNum(row) {
      this.boxid = row.id
      this.drawer = true
      this.boxloading = true
      const res = await lookBoxNum({
        page: this.boxcurrentPage,
        limit: this.boxpageSize
      })
    },
    //获取列表
    async getList() {
      this.loading = true
      const res = await blinboxList({
        page: this.currentPage,
        limit: this.pageSize,
        keywords: this.query.keywords,
        type: this.query.type,
        is_template: this.activeName
      })
      this.loading = false
      this.total = res.count
      this.tableData = res.data
      console.log(
        res.data
          .filter((item) => item.price <= 10)
          .map((item) => item.id)
          .join(',')
      )
      console.log(
        res.data
          .filter((item) => item.price > 10 && item.price <= 25)
          .map((item) => item.id)
          .join(',')
      )
      console.log(
        res.data
          .filter((item) => item.price > 25)
          .map((item) => item.id)
          .join(',')
      )
    },
    queryAsk() {
      console.log(this.query)
      this.currentPage = 1
      this.getList()
    },
    queryReset() {
      this.resetForm('query')
      this.total = 0
      this.currentPage = 1
      this.pageSize = 10
      this.query.keywords = ''
      this.query.type = '0'
      this.getList()
    },
    addList(command) {
      console.log(command)
      if (command == 1) {
        this.$router.push({ name: 'AddBoxTX', query: { title: '添加' } })
      } else if (command == 2) {
        this.$router.push({ name: 'AddBoxWX', query: { title: '添加' } })
      } else if (command == 3) {
        this.$router.push({
          name: 'AddTreasureHunt',
          query: { title: '添加' }
        })
      }
    },
    // 表格操作
    async handleDel(row) {
      try {
        const res = await delBox({ id: row.id })
        console.log(res)
        this.getList()
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      } catch (error) {
        this.$message.error('删除失败')
        console.log(error)
      }
    },
    handleEdite(row) {
      if (row.type == 1) {
        this.$router.push({
          name: 'AddBoxTX',
          query: { id: row.id, title: '编辑' }
        })
      } else if (row.type == 2) {
        this.$router.push({
          name: 'AddBoxWX',
          query: { id: row.id, title: '编辑' }
        })
      } else if (row.type == 3) {
        this.$router.push({
          name: 'AddTreasureHunt',
          query: { id: row.id, title: '编辑' }
        })
      }
    },
    //复制盲盒模板
    async copyMH(row) {
      try {
        await copyBox({ id: row.id, type: 1 })
        this.activeName = '0'
        this.getList()
        this.$message({
          message: '复制成功',
          type: 'success'
        })
      } catch (error) {
        console.log(error)
        this.$message.error('复制失败')
      }
    },
    async copyMB(row) {
      try {
        await copyBox({ id: row.id, type: 2 })
        this.getList()
        this.$message({
          message: '复制成功',
          type: 'success'
        })
      } catch (error) {
        console.log(error)
        this.$message.error('复制失败')
      }
    },
    //上架
    async grounding(row) {
      const res = await grounding({ id: row.id })
      if (res.st == 1) {
        this.getList()
        if (row.is_show == 0) {
          this.$message({
            message: '上架成功',
            type: 'success'
          })
        } else if (row.is_show == 1) {
          this.$message({
            message: '下架成功',
            type: 'success'
          })
        }
      } else if (res.st == -1) {
        this.$message.error(res.msg)
      }
    },
    //添加箱数
    addBoxNum(row) {
      this.dialogVisible = true
      this.addform.id = row.id
    },
    handleClose(done) {
      this.addform = { id: '', num: '' }
      this.dialogVisible = false
      done()
    },
    subCancel() {
      this.addform = { id: '', num: '' }
      this.dialogVisible = false
    },
    async addBoxNumSub() {
      try {
        await addBoxNum({ ...this.addform })
        this.getList()
        this.dialogVisible = false
        this.$message({
          message: '箱数设置成功',
          type: 'success'
        })
      } catch (error) {
        console.log(error)
        this.$message.error('箱数设置失败')
      }
    },
    // 箱数列表
    async boxNumList(id) {
      this.boxloading = true
      const res = await lookBoxNum({
        page: this.boxcurrentPage,
        limit: this.boxpageSize,
        box_id: this.boxid
      })
      console.log(res)
      this.boxloading = false
      this.drawtableData = res.data
      this.drawtableData.forEach((item) => {
        if (item.over_time == 0) {
          item.over_time = '-'
        } else {
          item.over_time = parseTime(item.over_time, '{y}-{m}-{d} {h}:{i}:{s}')
        }
      })
      this.boxtotal = res.count
    },
    lookBoxNum(row) {
      this.boxid = row.id
      this.boxNumList()
      this.drawer = true
    },
    //分页改变
    boxcurrentChange(current) {
      this.boxcurrentPage = current
      this.boxNumList()
    },
    drawhandleClose(done) {
      done()
    },
    //分页改变
    currentChange(current) {
      this.currentPage = current
      this.getList()
    },
    async handleClick(tab, event) {
      await this.getList()
      this.activeName = tab.name
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script> 

<style lang="scss" scoped>
.query-card {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.box-card {
  margin-bottom: 20px;
}
.search {
  display: flex;
  align-items: center;
}

::v-deep .el-drawer.rtl {
  padding-bottom: 20px;
  width: 900px !important;
  overflow: auto;
}
.query-card {
  ::v-deep .el-form {
    display: flex;
  }
}
.el-dropdown {
  vertical-align: top;
}
.el-dropdown + .el-dropdown {
  margin-left: 15px;
}
.el-icon-arrow-down {
  font-size: 12px;
}
</style>